package cn.edu.yzu.scholarship.controller;

import java.util.HashMap;
import java.util.Map;

import cn.edu.yzu.scholarship.constant.C;
import cn.edu.yzu.scholarship.kit.Sak;
import cn.edu.yzu.scholarship.model.Freeze;
import cn.edu.yzu.scholarship.model.Group;
import cn.edu.yzu.scholarship.model.Student;
import cn.edu.yzu.scholarship.model.Teacher;
import cn.edu.yzu.scholarship.pojo.Pager;
import cn.edu.yzu.scholarship.validator.ChangeAdminPwdValidator;
import cn.edu.yzu.scholarship.validator.ChangePwdValidator;
import cn.edu.yzu.scholarship.validator.FreezeStudentValidator;
import cn.edu.yzu.scholarship.validator.LoginValidator;
import cn.edu.yzu.scholarship.validator.ThawValidator;

import com.jfinal.aop.Before;
import com.jfinal.core.ActionKey;
import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;

public class UserCtrler extends Controller {
	
	//----------------登陆\注销部分---------------------
	@ActionKey("/")
	public void index() {
		render("/index.html");
	}
	
	@Before(LoginValidator.class)
	public void login() {
		Record one = null;
		int userType = getParaToInt("userType");
		switch(userType) {
		case C.UT_STUDENT: one = Student.getRecord(getPara("loginName"), getPara("loginPwd"));break;
		case C.UT_TEACHER: one = Teacher.getTeacher(getPara("loginName"), getPara("loginPwd"));break;
		case C.UT_SYSTEM: one = Teacher.getTeacher(getPara("loginName"), getPara("loginPwd"));break;
		case C.UT_CONTROL: one = Teacher.getTeacher(getPara("loginName"), getPara("loginPwd"));break;
		}
		doLogin(one,userType);
	}

	private void doLogin(Record rec,int userType) {
		if(rec == null) {
			renderJson("errorInfo","用户名或密码有误！");
			return;
		}
		
		this.setSessionAttr("userType", userType);
		this.setSessionAttr("user", rec);
		renderJson("errorInfo","none");//通知页面，登陆过程没有问题。
		
	}
	
	public void logout() {
		this.removeSessionAttr("userType");
		this.removeSessionAttr("user");
		this.redirect("/login.html");
	}
	
	@Before(ChangePwdValidator.class)
	public void changePwd() {
		Record one = this.getSessionAttr("user");
		one.set("loginPwd", this.getPara("newPwd"));
		
		switch((Integer)getSessionAttr("userType")) {
		case C.UT_STUDENT: Student.update(one);break;
		case C.UT_TEACHER: Teacher.update(one);break;
		}
		
		renderText(Sak.toJsonStr("errorInfo", "none"));//通知页面，修改密码过程没有问题。
		//renderJson("errorInfo","none");//IE form submit bug!
	}
	
	@Before(ChangeAdminPwdValidator.class)
	public void changeAdminPwd() {
		Record one = this.getSessionAttr("user");
		one.set("managePwd", this.getPara("newPwd"));
		Teacher.update(one);
		renderText(Sak.toJsonStr("errorInfo", "none"));//通知页面，修改密码过程没有问题。
		//renderJson("errorInfo","none");//IE form submit bug!
	}
	
	public void info() {
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("userType",getSessionAttr("userType"));
		map.put("user",getSessionAttr("user"));
		renderJson(map);
	}

	//---------------学生/老师信息部分-----------------------
	public void students() {
		Map<String,String> params = new HashMap<String,String>();
		params.put("college", getPara("college", "-"));
		params.put("major", getPara("major", "-"));
		params.put("year", getPara("year", "-"));
		params.put("classify", getPara("classify", "-"));
		params.put("groupId", getPara("groupId", "-"));
		
		renderJson(Student.paginate(getParaToInt("page"), getParaToInt("rows"),params));
	}
	
	public void freezeStus() {
		Map<String,String> params = new HashMap<String,String>();
		params.put("college", getPara("college", "-"));
		params.put("major", getPara("major", "-"));
		params.put("year", getPara("year", "-"));
		params.put("classify", getPara("classify", "-"));
		params.put("groupId", getPara("groupId", "-"));
		
		renderJson(Student.paginateFree(getParaToInt("page"), getParaToInt("rows"),params));
	}
	
	//----- 毕业生管理 -----
	
	public void graduates() {
		renderJson(Pager.toPager(Db.paginate(getParaToInt("page"), getParaToInt("rows"), "select * ", "from student_his")));
	}
	
	public void inGraduates() {
		for(String xh : getPara("xhs").split(",")) {
			Db.update("insert into student_his select * from student where xh = ?", xh);
			Db.update("delete from student where xh = ?", xh);
			Db.update("delete from stugrouplist where xh = ?",xh);//名单中的信息，不可撤销
		}
		
		renderJson("errorInfo","none");
	}
	
	public void outGraduates() {
		for(String xh : getPara("xhs").split(",")) {
			Db.update("insert into student select * from student_his where xh = ?", xh);
			Db.update("delete from student_his where xh = ?", xh);
		}
		
		renderJson("errorInfo","none");
	}
	
	/**
	 * 冻结/解冻用户
	 */
	@Before(FreezeStudentValidator.class)
	public void freeze() {
		for(String xh : getPara("xhs").split(",")) {
			Freeze.insertOne(xh, getPara("startdate"), getPara("enddate"), getPara("reason"),getPara("scholarshipId"));
		}
		renderJson("errorInfo","none");
	}
	
	public void freezeList() {
		renderJson(Freeze.findFreezingList(getPara("scholarshipId")));
	}
	
	public void freezeHis() {
		String sql1 = (getPara("xh", "-") == C.PARAM_ALL ? "" : "where student.xh = '" + getPara("xh") + "' ");
		renderJson(Db.find("select student.xm,freeze_his.* from student left join freeze_his on student.xh = freeze_his.xh " + sql1 + "order by freeze_his.createtime desc"));
	}
	
	@Before(ThawValidator.class)
	public void thaw() {
		for(String xh : getPara("xhs").split(",")) {
			Freeze.deleteOne(xh,getPara("scholarshipId"),getPara("reason"));
		}
		renderJson("errorInfo","none");
	}
	
	//-------------名单管理---------------
	public void group() {
		renderJson(Group.findAllMain());
	}
	
	public void groupList() {
		renderJson(Group.paginate(getPara("groupId"), getParaToInt("page"), getParaToInt("rows")));
	}

	public void groupAct() {
		String act = getPara("action");
		String groupId = getPara("groupId");
		String groupName = getPara("groupName");
		if("add".equals(act)) Group.createMain(groupName);
		else if("edit".equals(act)) Group.updateMain(groupId, groupName);
		else if("del".equals(act)) {
			Group.deleteAllByGroupId(groupId);
			Group.deleteMainById(groupId);
		}
		
		renderJson("errorInfo","none");
	}

	public void groupListAct() {
		String act = getPara("action");
		String groupId = getPara("groupId");
		String xhs = getPara("xhs");
		if("add".equals(act)) doAddGroupList(groupId, xhs);
		else if("del".equals(act)) doDelGroupList(groupId, xhs);
		
		renderJson("errorInfo","none");
	}

	private void doDelGroupList(String groupId, String xhs) {
		for(String xh : xhs.split(",")) {
			Group.deleteOneStu(groupId, xh);
		}
	}

	private void doAddGroupList(String groupId, String xhs) {
		for(String xh : xhs.split(",")) {
			Group.deleteOneStu(groupId, xh);
			Group.insertOneStu(groupId, xh);
		}
	}

}
